# resume_parser.py
# 提取简历中的有效信息
import os
import json
from utils.file_parser import FileParser

# 引入阿里云 Qwen 模型的调用配置
from openai import OpenAI
from config.API import api

client = OpenAI(
    api_key=api,
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"
)

class ResumeParser:
    def __init__(self, save_to_file: bool = False):
        self.extractor = FileParser()
        self.save_to_file = save_to_file

    def parse(self, filepath: str) -> dict:
        """
        提取上传文本中的文字内容, 调用大模型返回结构化信息。
        :param filepath: 简历文件路径
        :return: 结构化JSON对象(dict)
        """
        if not os.path.exists(filepath):
            raise FileNotFoundError(f"找不到文件：{filepath}")

        filename = os.path.basename(filepath)
        name_without_ext = os.path.splitext(filename)[0]

        # 提取纯文本
        raw_text = self.extractor.extract_text(filepath)

        # 保存原始文本用于调试
        # if self.save_to_file:
        #     raw_txt_path = f"data/samples/{name_without_ext}.txt"
        #     os.makedirs(os.path.dirname(raw_txt_path), exist_ok=True)
        #     with open(raw_txt_path, "w", encoding="utf-8") as f:
        #         f.write(raw_text)
        #     print(f"[✓] 原始文本已保存至 {raw_txt_path}")

        # 调用大模型结构化解析
        structured_data = self.extract_structured_resume(raw_text)

        # 保存结构化JSON结果
        if self.save_to_file and isinstance(structured_data, dict):
            json_path = f"data/structured_resume/{name_without_ext}.json"
            os.makedirs(os.path.dirname(json_path), exist_ok=True)
            with open(json_path, "w", encoding="utf-8") as f:
                json.dump(structured_data, f, ensure_ascii=False, indent=2)
            print(f"[✓] 结构化结果已保存至 {json_path}")

        return structured_data

    def extract_structured_resume(self, raw_text: str) -> dict:
        """
        调用LLM将纯文本简历转换为结构化信息。
        :param raw_text: 提取的简历文本
        :return: dict类型结构化信息
        """
        prompt = f"""你是一位人力资源专家。请将以下简历文本内容提取并转换为一个**合法的 JSON 字符串**，字段结构如下（严格遵循）：

        {{
        "name": "未知",
        "summary": "",
        "education": [{{"school": "", "major": "", "degree": "", "start": "", "end": ""}}],
        "work_experience": [{{"company": "", "position": "", "start": "", "end": "", "location": "", "responsibilities": []}}],
        "skills": {{
            "languages": [],
            "frameworks": [],
            "databases": [],
            "tools": [],
            "others": []
        }},
        "projects": [{{"name": "", "description": "", "technologies": []}}],
        "languages": []
        }}

        请严格遵循以下约束：
        - **只输出 JSON 对象内容，不要添加任何解释、注释或 Markdown 代码框（如```json）**
        - **不要包含 HTML、图片链接或 Markdown 内容（如 ![]()）**
        - 所有字段都应存在，即使值为空
        - 输出内容必须能直接被 Python 的 `json.loads()` 正确解析
        - 输出内容不需要被markdown语法块包裹, 应是完整的json文件内的内容

        以下是待处理的简历内容：
        \"\"\"{raw_text}\"\"\"
        """


        try:
            completion = client.chat.completions.create(
                model="qwen-plus",
                messages=[
                    {"role": "system", "content": "你是一位专业的简历解析器"},
                    {"role": "user", "content": prompt}
                ],
                temperature=0.2
            )
            content = completion.choices[0].message.content
            return json.loads(content)
        except json.JSONDecodeError:
            print("JSON 解析失败，请检查模型输出：")
            print(content)
            return {"error": "Invalid JSON", "raw_output": content}
        except Exception as e:
            return {"error": f"调用大模型失败: {str(e)}"}
